package com.terrace.core.spring.datasource.interceptor;

import java.lang.reflect.Method;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.terrace.core.spring.datasource.annotation.DataSource;
import com.terrace.core.spring.datasource.lookup.DataSourceHolder;
import com.terrace.core.spring.support.BaseAspectSupport;

/**
 * 数据源切面支撑类
 * 
 * @author jiangyg
 *
 */
public class DataSourceAspectSupport extends BaseAspectSupport {

	/**
	 * 日志
	 */
	protected static final Logger logger = LoggerFactory.getLogger(DataSourceAspectSupport.class);

	/**
	 * 执行切换数据源
	 */
	protected Object execute(DataSourceInvoker dataSourceInvoker, Object target, Method method, Object[] args) {
		
		// 获取注解所在类
		Class<?> targetClass = getTargetClass(target);
		
		// 获取类上的注解
		DataSource dataSourceClazz = targetClass.getAnnotation(DataSource.class);
		if (dataSourceClazz != null) {
			if (logger.isDebugEnabled()) {
				logger.debug("类[" + targetClass.getName() + "]注释数据源为：" + dataSourceClazz.name());
			}
		}
		
		// 试图获取要执行方法上的注解
		DataSource dataSourceMethod = method.getAnnotation(DataSource.class);
		if (dataSourceMethod != null) {
			if (logger.isDebugEnabled()) {
				logger.debug("类[" + targetClass.getName() + "]，方法[" + method.getName() + "]注释数据源为：" + dataSourceMethod.name());
			}
			// 设置数据源，方法级别注释最高
			DataSourceHolder.setDataSource(dataSourceMethod.name());
			return dataSourceInvoker.invoke();
		}
		
		DataSourceHolder.setDataSource(dataSourceClazz.name());

		return dataSourceInvoker.invoke();
	}
	
}
